<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <h2>{{id?'编辑':'新增'}}分类</h2>
    </div>
    <el-form :label-position="labelPosition" label-width="80px" @submit.native.prevent="saveCategory">
      <el-form-item label="分类名称" style="width: 50%;margin-left: 20%">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item style="margin-left: 35%">
        <el-button type="success" round  native-type="submit">提交</el-button>
      </el-form-item>

    </el-form>
  </el-card>
</template>

<script>
  export default {
    name: "CategoryEdit",
    props:['id'],
    data(){
      return {
        labelPosition: 'right',
        model:{
          name:''
        },
        parentsOptions:[]
      }
    },
    methods:{
      async saveCategory(){
        let result
        if(this.id){
          result = await this.$http.put(`/rest/categories/${this.id}`,this.model)
          this.$message({
            message: `修改分类${this.model.name}成功`,
            type: 'success'
          });
        }else {
          result = await this.$http.post('/rest/categories',this.model)
          if(result.status != 200){
            this.$message({
              message: `${result.data}`,
              type: 'warning'
            });
            this.model.name=''
          } else {
            this.$message({
              message: `创建分类${this.model.name}成功`,
              type: 'success'
            });
            this.$router.push('/categories/list')
          }
        }
      },
      async getCategoriesEditData(){
        const res =  await this.$http.get(`/rest/categories/${this.id}`)
        this.model = res.data
      },

    },
    created() {
      this.id ? this.getCategoriesEditData():''
    }
  }
</script>

<style lang="scss" scoped>

</style>
